{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "g_nWetWWd_ns"
      },
      "source": [
        "##### Copyright 2018 The TensorFlow Authors."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "2pHVBk_seED1"
      },
      "outputs": [],
      "source": [
        "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "N_fMsQ-N8I7j"
      },
      "outputs": [],
      "source": [
        "#@title MIT License\n",
        "#\n",
        "# Copyright (c) 2017 François Chollet\n",
        "#\n",
        "# Permission is hereby granted, free of charge, to any person obtaining a\n",
        "# copy of this software and associated documentation files (the \"Software\"),\n",
        "# to deal in the Software without restriction, including without limitation\n",
        "# the rights to use, copy, modify, merge, publish, distribute, sublicense,\n",
        "# and/or sell copies of the Software, and to permit persons to whom the\n",
        "# Software is furnished to do so, subject to the following conditions:\n",
        "#\n",
        "# The above copyright notice and this permission notice shall be included in\n",
        "# all copies or substantial portions of the Software.\n",
        "#\n",
        "# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n",
        "# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n",
        "# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n",
        "# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n",
        "# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n",
        "# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n",
        "# DEALINGS IN THE SOFTWARE."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "pZJ3uY9O17VN"
      },
      "source": [
        "# Save and restore models"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "M4Ata7_wMul1"
      },
      "source": [
        "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/r1/tutorials/keras/save_and_restore_models.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://github.com/tensorflow/docs/blob/master/site/en/r1/tutorials/keras/save_and_restore_models.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n",
        "  </td>\n",
        "</table>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "M4Ata7_wMul1"
      },
      "source": [
        "> Note: This is an archived TF1 notebook. These are configured\n",
        "to run in TF2's \n",
        "[compatbility mode](https://www.tensorflow.org/guide/migrate)\n",
        "but will run in TF1 as well. To use TF1 in Colab, use the\n",
        "[%tensorflow_version 1.x](https://colab.research.google.com/notebooks/tensorflow_version.ipynb)\n",
        "magic."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "mBdde4YJeJKF"
      },
      "source": [
        "Model progress can be saved during—and after—training. This means a model can resume where it left off and avoid long training times. Saving also means you can share your model and others can recreate your work. When publishing research models and techniques, most machine learning practitioners share:\n",
        "\n",
        "* code to create the model, and\n",
        "* the trained weights, or parameters, for the model\n",
        "\n",
        "Sharing this data helps others understand how the model works and try it themselves with new data.\n",
        "\n",
        "Caution: Be careful with untrusted code—TensorFlow models are code. See [Using TensorFlow Securely](https://github.com/tensorflow/tensorflow/blob/master/SECURITY.md) for details.\n",
        "\n",
        "### Options\n",
        "\n",
        "There are different ways to save TensorFlow models—depending on the API you're using. This guide uses [tf.keras](https://www.tensorflow.org/r1/guide/keras), a high-level API to build and train models in TensorFlow. For other approaches, see the TensorFlow  [Save and Restore](https://www.tensorflow.org/r1/guide/saved_model) guide or [Saving in eager](https://www.tensorflow.org/r1/guide/eager#object-based_saving).\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "xCUREq7WXgvg"
      },
      "source": [
        "## Setup\n",
        "\n",
        "### Installs and imports"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "7l0MiTOrXtNv"
      },
      "source": [
        "Install and import TensorFlow and dependencies:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "RzIOVSdnMYyO"
      },
      "outputs": [],
      "source": [
        "!pip install h5py pyyaml\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "SbGsznErXWt6"
      },
      "source": [
        "### Get an example dataset\n",
        "\n",
        "We'll use the [MNIST dataset](http://yann.lecun.com/exdb/mnist/) to train our model to demonstrate saving weights. To speed up these demonstration runs, only use the first 1000 examples:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "7Nm7Tyb-gRt-"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "\n",
        "import tensorflow.compat.v1 as tf\n",
        "\n",
        "from tensorflow import keras\n",
        "\n",
        "tf.__version__"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "9rGfFwE9XVwz"
      },
      "outputs": [],
      "source": [
        "(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data()\n",
        "\n",
        "train_labels = train_labels[:1000]\n",
        "test_labels = test_labels[:1000]\n",
        "\n",
        "train_images = train_images[:1000].reshape(-1, 28 * 28) / 255.0\n",
        "test_images = test_images[:1000].reshape(-1, 28 * 28) / 255.0"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "anG3iVoXyZGI"
      },
      "source": [
        "### Define a model"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "wynsOBfby0Pa"
      },
      "source": [
        "Let's build a simple model we'll use to demonstrate saving and loading weights."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "0HZbJIjxyX1S"
      },
      "outputs": [],
      "source": [
        "# Returns a short sequential model\n",
        "def create_model():\n",
        "  model = tf.keras.models.Sequential([\n",
        "    keras.layers.Dense(512, activation=tf.keras.activations.relu, input_shape=(784,)),\n",
        "    keras.layers.Dropout(0.2),\n",
        "    keras.layers.Dense(10, activation=tf.keras.activations.softmax)\n",
        "  ])\n",
        "\n",
        "  model.compile(optimizer=tf.keras.optimizers.Adam(),\n",
        "                loss=tf.keras.losses.sparse_categorical_crossentropy,\n",
        "                metrics=['accuracy'])\n",
        "\n",
        "  return model\n",
        "\n",
        "\n",
        "# Create a basic model instance\n",
        "model = create_model()\n",
        "model.summary()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "soDE0W_KH8rG"
      },
      "source": [
        "## Save checkpoints during training"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "mRyd5qQQIXZm"
      },
      "source": [
        "The primary use case is to automatically save checkpoints *during* and at *the end* of training. This way you can use a trained model without having to retrain it, or pick-up training where you left of—in case the training process was interrupted.\n",
        "\n",
        "`tf.keras.callbacks.ModelCheckpoint` is a callback that performs this task. The callback takes a couple of arguments to configure checkpointing.\n",
        "\n",
        "### Checkpoint callback usage\n",
        "\n",
        "Train the model and pass it the `ModelCheckpoint` callback:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "IFPuhwntH8VH"
      },
      "outputs": [],
      "source": [
        "checkpoint_path = \"training_1/cp.ckpt\"\n",
        "checkpoint_dir = os.path.dirname(checkpoint_path)\n",
        "\n",
        "# Create checkpoint callback\n",
        "cp_callback = tf.keras.callbacks.ModelCheckpoint(checkpoint_path,\n",
        "                                                 save_weights_only=True,\n",
        "                                                 verbose=1)\n",
        "\n",
        "model = create_model()\n",
        "\n",
        "model.fit(train_images, train_labels,  epochs = 10,\n",
        "          validation_data = (test_images,test_labels),\n",
        "          callbacks = [cp_callback])  # pass callback to training\n",
        "\n",
        "# This may generate warnings related to saving the state of the optimizer.\n",
        "# These warnings (and similar warnings throughout this notebook)\n",
        "# are in place to discourage outdated usage, and can be ignored."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "rlM-sgyJO084"
      },
      "source": [
        "This creates a single collection of TensorFlow checkpoint files that are updated at the end of each epoch:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "gXG5FVKFOVQ3"
      },
      "outputs": [],
      "source": [
        "!ls {checkpoint_dir}"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "wlRN_f56Pqa9"
      },
      "source": [
        "Create a new, untrained model. When restoring a model from only weights, you must have a model with the same architecture as the original model. Since it's the same model architecture, we can share weights despite that it's a different *instance* of the model.\n",
        "\n",
        "Now rebuild a fresh, untrained model, and evaluate it on the test set. An untrained model will perform at chance levels (~10% accuracy):"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Fp5gbuiaPqCT"
      },
      "outputs": [],
      "source": [
        "model = create_model()\n",
        "\n",
        "loss, acc = model.evaluate(test_images,  test_labels, verbose=2)\n",
        "print(\"Untrained model, accuracy: {:5.2f}%\".format(100*acc))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1DTKpZssRSo3"
      },
      "source": [
        "Then load the weights from the checkpoint, and re-evaluate:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "2IZxbwiRRSD2"
      },
      "outputs": [],
      "source": [
        "model.load_weights(checkpoint_path)\n",
        "loss,acc = model.evaluate(test_images,  test_labels, verbose=2)\n",
        "print(\"Restored model, accuracy: {:5.2f}%\".format(100*acc))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "bpAbKkAyVPV8"
      },
      "source": [
        "### Checkpoint callback options\n",
        "\n",
        "The callback provides several options to give the resulting checkpoints unique names, and adjust the checkpointing frequency.\n",
        "\n",
        "Train a new model, and save uniquely named checkpoints once every 5-epochs:\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "mQF_dlgIVOvq"
      },
      "outputs": [],
      "source": [
        "# include the epoch in the file name. (uses `str.format`)\n",
        "checkpoint_path = \"training_2/cp-{epoch:04d}.ckpt\"\n",
        "checkpoint_dir = os.path.dirname(checkpoint_path)\n",
        "\n",
        "cp_callback = tf.keras.callbacks.ModelCheckpoint(\n",
        "    checkpoint_path, verbose=1, save_weights_only=True,\n",
        "    # Save weights, every 5-epochs.\n",
        "    period=5)\n",
        "\n",
        "model = create_model()\n",
        "model.save_weights(checkpoint_path.format(epoch=0))\n",
        "model.fit(train_images, train_labels,\n",
        "          epochs = 50, callbacks = [cp_callback],\n",
        "          validation_data = (test_images,test_labels),\n",
        "          verbose=0)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1zFrKTjjavWI"
      },
      "source": [
        "Now, look at the resulting checkpoints and choose the latest one:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "p64q3-V4sXt0"
      },
      "outputs": [],
      "source": [
        "! ls {checkpoint_dir}"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "1AN_fnuyR41H"
      },
      "outputs": [],
      "source": [
        "latest = tf.train.latest_checkpoint(checkpoint_dir)\n",
        "latest"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Zk2ciGbKg561"
      },
      "source": [
        "Note: the default tensorflow format only saves the 5 most recent checkpoints.\n",
        "\n",
        "To test, reset the model and load the latest checkpoint:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "3M04jyK-H3QK"
      },
      "outputs": [],
      "source": [
        "model = create_model()\n",
        "model.load_weights(latest)\n",
        "loss, acc = model.evaluate(test_images,  test_labels, verbose=2)\n",
        "print(\"Restored model, accuracy: {:5.2f}%\".format(100*acc))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "c2OxsJOTHxia"
      },
      "source": [
        "## What are these files?"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "JtdYhvWnH2ib"
      },
      "source": [
        "The above code stores the weights to a collection of [checkpoint](https://www.tensorflow.org/r1/guide/saved_model#save_and_restore_variables)-formatted files that contain only the trained weights in a binary format. Checkpoints contain:\n",
        "* One or more shards that contain your model's weights.\n",
        "* An index file that indicates which weights are stored in a which shard.\n",
        "\n",
        "If you are only training a model on a single machine, you'll have one shard with the suffix: `.data-00000-of-00001`"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "S_FA-ZvxuXQV"
      },
      "source": [
        "## Manually save weights\n",
        "\n",
        "Above you saw how to load the weights into a model.\n",
        "\n",
        "Manually saving the weights is just as simple, use the `Model.save_weights` method."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "R7W5plyZ-u9X"
      },
      "outputs": [],
      "source": [
        "# Save the weights\n",
        "model.save_weights('./checkpoints/my_checkpoint')\n",
        "\n",
        "# Restore the weights\n",
        "model = create_model()\n",
        "model.load_weights('./checkpoints/my_checkpoint')\n",
        "\n",
        "loss,acc = model.evaluate(test_images,  test_labels, verbose=2)\n",
        "print(\"Restored model, accuracy: {:5.2f}%\".format(100*acc))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "kOGlxPRBEvV1"
      },
      "source": [
        "## Save the entire model\n",
        "\n",
        "The entire model can be saved to a file that contains the weight values, the model's configuration, and even the optimizer's configuration (depends on set up). This allows you to checkpoint a model and resume training later—from the exact same state—without access to the original code.\n",
        "\n",
        "Saving a fully-functional model is very useful—you can load them in TensorFlow.js ([HDF5](https://js.tensorflow.org/r1/tutorials/import-keras.html), [Saved Model](https://js.tensorflow.org/r1/tutorials/import-saved-model.html)) and then train and run them in web browsers, or convert them to run on mobile devices using TensorFlow Lite ([HDF5](https://www.tensorflow.org/lite/convert/python_api#exporting_a_tfkeras_file_), [Saved Model](https://www.tensorflow.org/lite/convert/python_api#exporting_a_savedmodel_))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "SkGwf-50zLNn"
      },
      "source": [
        "### As an HDF5 file\n",
        "\n",
        "Keras provides a basic save format using the [HDF5](https://en.wikipedia.org/wiki/Hierarchical_Data_Format) standard. For our purposes, the saved model can be treated as a single binary blob."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "m2dkmJVCGUia"
      },
      "outputs": [],
      "source": [
        "model = create_model()\n",
        "\n",
        "model.fit(train_images, train_labels, epochs=5)\n",
        "\n",
        "# Save entire model to a HDF5 file\n",
        "model.save('my_model.h5')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "GWmttMOqS68S"
      },
      "source": [
        "Now recreate the model from that file:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "5NDMO_7kS6Do"
      },
      "outputs": [],
      "source": [
        "# Recreate the exact same model, including weights and optimizer.\n",
        "new_model = keras.models.load_model('my_model.h5')\n",
        "new_model.summary()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "JXQpbTicTBwt"
      },
      "source": [
        "Check its accuracy:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "jwEaj9DnTCVA"
      },
      "outputs": [],
      "source": [
        "loss, acc = new_model.evaluate(test_images,  test_labels, verbose=2)\n",
        "print(\"Restored model, accuracy: {:5.2f}%\".format(100*acc))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "dGXqd4wWJl8O"
      },
      "source": [
        "This technique saves everything:\n",
        "\n",
        "* The weight values\n",
        "* The model's configuration(architecture)\n",
        "* The optimizer configuration\n",
        "\n",
        "Keras saves models by inspecting the architecture. Currently, it is not able to save TensorFlow optimizers (from `tf.train`). When using those you will need to re-compile the model after loading, and you will lose the state of the optimizer.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "kPyhgcoVzqUB"
      },
      "source": [
        "### As a `saved_model`"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "LtcN4VIb7JkK"
      },
      "source": [
        "Caution: This method of saving a `tf.keras` model is experimental and may change in future versions."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "DSWiSB0Q8c46"
      },
      "source": [
        "Build a fresh model:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "sI1YvCDFzpl3"
      },
      "outputs": [],
      "source": [
        "model = create_model()\n",
        "\n",
        "model.fit(train_images, train_labels, epochs=5)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "iUvT_3qE8hV5"
      },
      "source": [
        "Create a `saved_model`:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "sq8fPglI1RWA"
      },
      "outputs": [],
      "source": [
        "import time\n",
        "\n",
        "saved_model_path = \"./saved_models/\"+str(int(time.time()))\n",
        "model.save(saved_model_path, save_format='tf')\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MjpmyPfh8-1n"
      },
      "source": [
        "Have a look in the directory:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ZtOvxA7V0iTv"
      },
      "outputs": [],
      "source": [
        "!ls {saved_model_path}"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "B7qfpvpY9HCe"
      },
      "source": [
        "Load the the saved model."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "0YofwHdN0pxa"
      },
      "outputs": [],
      "source": [
        "new_model = tf.keras.models.load_model(saved_model_path)\n",
        "new_model"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "uWwgNaz19TH2"
      },
      "source": [
        "Run the restored model."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Pc9e6G6w1AWG"
      },
      "outputs": [],
      "source": [
        "# The model has to be compiled before evaluating.\n",
        "# This step is not required if the saved model is only being deployed.\n",
        "\n",
        "new_model.compile(optimizer=tf.keras.optimizers.Adam(),\n",
        "              loss=tf.keras.losses.sparse_categorical_crossentropy,\n",
        "              metrics=['accuracy'])\n",
        "\n",
        "# Evaluate the restored model.\n",
        "loss, acc = new_model.evaluate(test_images,  test_labels, verbose=2)\n",
        "print(\"Restored model, accuracy: {:5.2f}%\".format(100*acc))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "eUYTzSz5VxL2"
      },
      "source": [
        "## What's Next\n",
        "\n",
        "That was a quick guide to saving and loading in with `tf.keras`.\n",
        "\n",
        "* The [tf.keras guide](https://www.tensorflow.org/r1/guide/keras) shows more about saving and loading models with `tf.keras`.\n",
        "\n",
        "* See [Saving in eager](https://www.tensorflow.org/r1/guide/eager#object_based_saving) for saving during eager execution.\n",
        "\n",
        "* The [Save and Restore](https://www.tensorflow.org/r1/guide/saved_model) guide has low-level details about TensorFlow saving."
      ]
    }
  ],
  "metadata": {
    "accelerator": "GPU",
    "colab": {
      "collapsed_sections": [],
      "name": "save_and_restore_models.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
